<?php
class news extends spController{
	public function __construct() {
		parent::__construct();
		$this -> _controller = 'news';
		$this -> _pk = spClass('MNews') -> pk;
		$this -> _attributes = spClass('MNews') -> getAttributes();
		$this -> _attributeFormset = spClass('MNews') -> getAttributeFormsets();
		spAddViewFunction('cbForm',array('LibCodeBuilder','cbFormWidget'));
	}
	
	public function index(){
		$this -> tpl_page = $page = $this -> spArgs('page',1);
		$this -> tpl_datas = spClass('MNews') -> spPager($page, 30) -> findAll();
		$this -> tpl_pager = spClass('MNews') -> spPager() -> getPager();
		$this -> display('news/index.html');
	}
	
	public function view(){
		$condition = array();
		$condition[$this->_pk] = $this -> spArgs('id');
		$this -> tpl_data = spClass('MNews') -> find($condition);
		$this -> display('news/view.html');
	}
	
	public function create(){
		if($_POST){
			$rows = spClass('spArgs')->get($this->_controller, null, 'post');
			$rows['date'] = date("Y-m-d H:i:s");
			if(($id = spClass('MNews')->create($rows)))
				$this ->success ('新增数据成功',  spUrl ($this->_controller, 'view', array('id'=>$id)));
			else
				$this ->error ('新增数据失败', 'javascript:history.go(-1)');
		}
		$this ->display('news/create.html');
	}
	
	public function update(){
		$condition = array();
		$condition[$this->_pk] = $this -> spArgs('id');
		if($_POST){
			$rows = spClass('spArgs')->get($this->_controller, null, 'post');
			if(spClass('MNews')->update($condition,$rows))
				$this ->success ('编辑数据成功',  spUrl ($this->_controller, 'view', array('id'=>$this -> spArgs('id'))));
			else
				$this ->error ('编辑数据失败', 'javascript:history.go(-1)');
		}
		$this -> tpl_data = spClass('MNews') -> find($condition);
		$this ->display('news/update.html');
	}
	
	public function delete(){
		$condition = array();
		$condition[$this->_pk] = $this -> spArgs('id');
		$success = spClass('MNews') -> delete($condition);
		if($success)
			$this ->success('删除成功', $this->spArgs('redirect','javascript:history.go(-1)'));
		else
			$this ->error('删除失败', $this->spArgs('redirect','javascript:history.go(-1)'));
	}
	
	public function search(){
		if($_POST){
			$this -> tpl_keyword = $conditions = spClass('spArgs')->get($this->_controller, null, 'post');
			$this -> tpl_searchType = $searchType = spClass('spArgs')->get($this->_controller.'_searchType', null, 'post');
			$where = array();
			foreach($conditions as $key => $value){
				if(empty($value)) continue;
				if(empty($this->_attributes[$key])) continue;
				if($searchType[$key] == 1) $where[] = ' '.$key.' LIKE '.spClass('MNews')->escape($value).' ';
				else $where[] = ' '.$key.' LIKE '.spClass('MNews')->escape('%'.$value.'%').' ';
			}
			$this -> tpl_page = $page = $this -> spArgs('page',1);
			$this -> tpl_datas = spClass('MNews') -> spPager($page, 30) -> findAll(implode('AND',$where));
			$this -> tpl_pager = spClass('MNews') -> spPager() -> getPager();
		}
		$this -> display('news/search.html');
	}
}